package com.nt.train.controller;
import com.nt.train.entity.StudentPO;
import com.nt.train.service.StudentService;
import com.nt.train.utils.JsonUtil;
import com.nt.train.utils.ResultUtil;
import com.nt.train.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * bean 演示 -01
 * 演示正常开发student 增删改查模块
 * @author hlf
 * @version 1.0
 * @date 2022/7/28 8:51
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentService  studentService ;

    @PostMapping("/findPageList/{pageIndex}/{pageSize}")
    public ResponseVO findPageList(@PathVariable Integer pageIndex,@PathVariable Integer pageSize,@RequestBody StudentPO studentPO) {
        System.out.println("接收参数结果："+studentPO);
        List<StudentPO>  pageList = studentService.selectStudent();
        Map<String,Object>  resultMap = new HashMap<>();
        resultMap.put("pageIndex",pageIndex);
        resultMap.put("pageSize",pageSize);
        resultMap.put("data",pageList);
        return ResultUtil.success("成功",resultMap);
    }

    @PostMapping(value = "/add")
    public ResponseVO add(@RequestBody StudentPO student) {
        System.out.println("接收参数结果："+student);
        studentService.addStudent(student);
        return ResultUtil.success("成功",student);
    }

    @PostMapping("/edit")
    public ResponseVO edit(@RequestBody StudentPO student) {
        System.out.println("接收参数结果："+student);
        try {
            studentService.updateStudent(student);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("修改失败！");
        }
        return ResultUtil.success("成功",student);
    }

    @PostMapping("/findById/{id}")
    public ResponseVO findById(@PathVariable Integer id) {
        System.out.println("接收参数结果："+id);
        return ResultUtil.success(null, studentService.getByPrimaryKey(id));

    }

    @PostMapping(value = "/delByIds")
    public ResponseVO delByIds(@RequestBody Long[] ids) {
        System.out.println("接收参数结果："+JsonUtil.toString(ids));
        if (null == ids) {
            return ResultUtil.error(500, "请至少选择一条记录");
        }
        for (Long id : ids) {
            studentService.delStudentById(id);
        }
        return ResultUtil.success("成功删除 [" + ids.length + "] 个学生",ids);
    }

    @PostMapping(value = "/delete2")
    public ResponseVO delete2(@RequestParam("ids[]") Long[] ids) {
        System.out.println("接收参数结果："+JsonUtil.toString(ids));
        if (null == ids) {
            return ResultUtil.error(500, "请至少选择一条记录");
        }
        for (Long id : ids) {
            studentService.delStudentById(id);
        }
        return ResultUtil.success("成功删除 [" + ids.length + "] 个学生",ids);
    }
}
